<?php

namespace app\api\command;

use app\extra\wx\WxSdk;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Log;

class OrderNotice extends Command
{

    protected function configure()
    {
        $this->setName('order_notice')->setDescription('【有效时间】到期前72小时通知');
    }

    protected function execute(Input $input, Output $output)
    {
        ini_set('default_socket_timeout', -1);  //不超时
        $redis = new \Redis();
        $redis->pconnect(config('redis.host'), config('redis.port'), config('redis.timeout'));
        $redis->select(2);

        // 订单【有效时间】即将到期
        $redis->psubscribe(['__keyevent@2__:expired'], function ($redis, $pattern, $channel, $message) use ($output) {
            // 下发通知
            Db::startTrans();
            try {
                $find = Db::name('order')
                    ->alias('order')
                    ->join('user user', 'user.id = order.user_id', 'left')
                    ->join('gymnasium gymnasium', 'gymnasium.id = order.gymnasium_id', 'left')
                    ->field('user.id,user.open_id,gymnasium.name,order.good_name,order.validity_time')
                    ->where(['order.numbers' => $message])
                    ->find();

                $content = "尊敬的约汗么用户，您在【{$find['name']}】购买的【{$find['good_name']}】在72小时内到期，该会员卡在到期前48小时不可退款。请及时使用会员卡，祝您生活愉快！";
                Db::name('notice')->insert([
                    'user_id'       => $find['id'],
                    'content'       => $content,
                    'order_numbers' => $message,
                    'createtime'    => time(),
                    'updatetime'    => time(),
                ]);

                // 微信订阅通知
                $pay        = get_addon_config('epay');
                $app_id     = $pay['wechat']['app_id'];
                $app_secret = $pay['wechat']['app_secret'];
                $data       = [
                    'date3'  => ['value' => date("Y-m-d H:i:s", $find['validity_time'])],
                    'thing4' => ['value' => '您的会员卡即将到期，点击查看详情'],
                ];
                $result     = (new WxSdk($app_id, $app_secret))->subscribeSend($find['open_id'], 'kvmaVk0OuBOwrZKjTiMJ1je4JK6OeBzrtShS9lqakjU', 'pages/personal/system/index', $data);
                Log::info($result);
                Db::commit();
                Log::info('ORDER_NOTICE 订单号：' . $message);
            } catch (\Exception $e) {
                Db::rollback();
                // 记录错误日志
                Log::error('订单【有效时间】到期');
                Log::info('ORDER_NOTICE 订单号：' . $message);
                Log::error($e->getMessage());
            }
        });
    }
}

